package com.xiaoshuidi.cloud.module.rooms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.module.iot.api.device.DeviceApi;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.DeviceListByNosApiReqVO;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.DevicePriceVo;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.PullDeviceApiVo;
import com.xiaoshuidi.cloud.module.iot.common.ResultModel;
import com.xiaoshuidi.cloud.module.rooms.api.sdiot.IotRoomDeviceApi;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.iot.vo.DeviceReaVo;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomSdiotReadingOrder;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomSdiotReadingOrderRecord;
import com.xiaoshuidi.cloud.module.rooms.repository.IotDeviceRepository;
import com.xiaoshuidi.cloud.module.rooms.service.IotDeviceService;
import com.xiaoshuidi.cloud.module.rooms.service.RoomSdiotReadingOrderRecordService;
import com.xiaoshuidi.cloud.module.rooms.vo.PriceInfo;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomDeviceStairVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @BelongsProject: lease-module-rooms
 * @BelongsPackage: com.xiaoshuidi.cloud.module.rooms.service.impl
 * @Author: James
 * @CreateTime: 2023-05-29  09:10
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class IotDeviceServiceImpl implements IotDeviceService {
    @Autowired
    private IotDeviceRepository iotDeviceRepository;
    @Autowired
    DeviceApi deviceApi;
    @Autowired
    private IotRoomDeviceApi iotRoomDeviceApi;
    @Autowired
    private RoomSdiotReadingOrderRecordService roomSdiotReadingOrderRecordService;

//    @Override
//    public CommonResult<PageResult<DeviceReaVo>> getDeviceList(DeviceReaVo deviceReaVo) {
//        PageResult<DeviceReaVo> pageResult = new PageResult<>();
//        List<DeviceReaVo> reaVoList = new ArrayList<>();
//        Page<DeviceReaVo> deviceList = iotDeviceRepository.getDeviceList(deviceReaVo);
//        List<DeviceReaVo> list1 = deviceList.getRecords();
//        DeviceListByNosApiReqVO deviceListByNosReqVO = new DeviceListByNosApiReqVO();
//        List<String> list = new ArrayList<>();
//        for (DeviceReaVo device : list1) {
//            list.add(device.getDeviceNo());
//        }
//        deviceListByNosReqVO.setDeviceNos(list);
//        deviceListByNosReqVO.setPageSize(deviceReaVo.getPageSize());
//        deviceListByNosReqVO.setPageNo(deviceReaVo.getPageNo());
//        //根据device_no 列表批量查询设备列表接口
//        ResultModel<PageInfo<PullDeviceApiVo>> deviceListByDeviceNosPage = deviceApi.findDeviceListByDeviceNosPage(deviceListByNosReqVO);
//        log.info("根据device_no 列表批量查询设备列表接口返回:{}", JSONObject.toJSONString(deviceListByDeviceNosPage));
//        if (CollectionUtil.isNotEmpty(list1)) {
//            for (int i = 0; i < list1.size(); i++) {
//                DeviceReaVo deviceReaVo1 = new DeviceReaVo();
//                deviceReaVo1.setRoomName(list1.get(i).getRoomName());
//                deviceReaVo1.setUnitName(list1.get(i).getUnitName());
//                deviceReaVo1.setIsWhole(list1.get(i).getIsWhole());
//                deviceReaVo1.setSuperId(list1.get(i).getSuperId());
//                deviceReaVo1.setIsConcentrated(list1.get(i).getIsConcentrated());
//                deviceReaVo1.setDeviceNo(list1.get(i).getDeviceNo());
//                deviceReaVo1.setDeviceType(list1.get(i).getDeviceType());
//                deviceReaVo1.setDeviceThirdNo(list1.get(i).getDeviceThirdNo());
//                if (deviceListByDeviceNosPage.getCode().equals("0")) {
//                    if (null != deviceListByDeviceNosPage.getData()) {
//                        List<PullDeviceApiVo> pullDeviceApiVoPageInfo = deviceListByDeviceNosPage.getData().getList();
//                        if (null != pullDeviceApiVoPageInfo) {
//                            for (PullDeviceApiVo apiVo : pullDeviceApiVoPageInfo) {
//                                if (apiVo.getDeviceNo().equals(list.get(i))) {
//                                    deviceReaVo1.setBatteryLevel(apiVo.getBatteryLevel());
//                                    deviceReaVo1.setOnlineStatus(apiVo.getOnlineStatus());
//                                    deviceReaVo1.setPowerStatus(apiVo.getPowerStatus());
//                                    deviceReaVo1.setBrandNo(apiVo.getBrandNo());
//                                    deviceReaVo1.setApiNo(apiVo.getApiNo());
//                                    deviceReaVo1.setPrice(apiVo.getPrice());
//                                    deviceReaVo1.setCurrentReading(apiVo.getCurrentReading());
//                                    deviceReaVo1.setRemainingAmount(apiVo.getRemainingAmount());
//                                    deviceReaVo1.setUpdateTime(apiVo.getReportTime());
//                                }
//                            }
//                        }
//                    }
//                }
//                reaVoList.add(deviceReaVo1);
//            }
//        }
//        pageResult.setList(reaVoList);
//        pageResult.setTotal(deviceList.getTotal());
//        return CommonResult.success(pageResult);
//    }


    @Override
    public CommonResult<PageResult<DeviceReaVo>> getDeviceList(DeviceReaVo deviceReaVo) {
        PageResult<DeviceReaVo> pageResult = PageResult.empty();
        List<DeviceReaVo> reaVoList = new ArrayList<>();
        DeviceListByNosApiReqVO deviceListByNosReqVO = new DeviceListByNosApiReqVO();
        deviceListByNosReqVO.setDeviceType(deviceReaVo.getDeviceType());
        deviceListByNosReqVO.setPowerLeve(deviceReaVo.getPowerLeve());
        deviceListByNosReqVO.setOnlineStatus(deviceReaVo.getOnlineStatus());
        deviceListByNosReqVO.setPowerStatus(deviceReaVo.getPowerStatus());
        List<String> deviceNolist = new ArrayList<>();
        List<PullDeviceApiVo> pullList = new ArrayList<>();
        try {
            ResultModel<List<PullDeviceApiVo>> pullDeviceApiVoList = deviceApi.findDeviceList(deviceListByNosReqVO);
            log.info("根据设备号，电量在线状态 列表批量查询设备列表接口返回:{}", JSONObject.toJSONString(pullDeviceApiVoList));
            if (pullDeviceApiVoList.getCode().equals("0")) {
                if (CollectionUtils.isEmpty(pullDeviceApiVoList.getData())) {
                    //没有设备
                    return CommonResult.success(pageResult);
                } else {
                    pullList = pullDeviceApiVoList.getData();
                    deviceNolist = pullList.stream().map(PullDeviceApiVo::getDeviceNo).collect(Collectors.toList());
                }
            }
        } catch (Exception e) {
            log.info("根据设备号，电量在线状态 列表批量查询设备列表接口返回:{}", e.getStackTrace());
        }

        //查询
        deviceReaVo.setDeviceNos(deviceNolist);
        log.info("查询房间的设备信息参数:{}", deviceReaVo);
        Page<DeviceReaVo> deviceList = iotDeviceRepository.getDeviceList(deviceReaVo);
        List<DeviceReaVo> list1 = deviceList.getRecords();
        if (!CollectionUtils.isEmpty(list1)) {
            for (int i = 0; i < list1.size(); i++) {
                DeviceReaVo deviceReaVo1 = new DeviceReaVo();
                deviceReaVo1.setRoomName(list1.get(i).getRoomName());
                deviceReaVo1.setUnitName(list1.get(i).getUnitName());
                deviceReaVo1.setIsWhole(list1.get(i).getIsWhole());
                deviceReaVo1.setSuperId(list1.get(i).getSuperId());
                deviceReaVo1.setIsConcentrated(list1.get(i).getIsConcentrated());
                deviceReaVo1.setDeviceNo(list1.get(i).getDeviceNo());
                deviceReaVo1.setDeviceType(list1.get(i).getDeviceType());
                deviceReaVo1.setDeviceThirdNo(list1.get(i).getDeviceThirdNo());
                for (PullDeviceApiVo apiVo : pullList) {
                    if (apiVo.getDeviceNo().equals(deviceReaVo1.getDeviceNo())) {
                        deviceReaVo1.setBatteryLevel(apiVo.getBatteryLevel());
                        deviceReaVo1.setOnlineStatus(apiVo.getOnlineStatus());
                        deviceReaVo1.setPowerStatus(apiVo.getPowerStatus());
                        deviceReaVo1.setBrandNo(apiVo.getBrandNo());
                        deviceReaVo1.setApiNo(apiVo.getApiNo());
                        deviceReaVo1.setPrice(apiVo.getPrice());
                        deviceReaVo1.setCurrentReading(apiVo.getCurrentReading());
                        deviceReaVo1.setRemainingAmount(apiVo.getRemainingAmount());
                        deviceReaVo1.setUpdateTime(apiVo.getReportTime());
                    }
                }
                reaVoList.add(deviceReaVo1);
            }
        }
        pageResult.setList(reaVoList);
        pageResult.setTotal(deviceList.getTotal());
        return CommonResult.success(pageResult);
    }

    @Override
    public CommonResult<List<DeviceReaVo>> getDeviceListNoPages(DeviceReaVo deviceReaVo) {
        List<DeviceReaVo> reaVoList = new ArrayList<>();
        DeviceListByNosApiReqVO deviceListByNosReqVO = new DeviceListByNosApiReqVO();
        deviceListByNosReqVO.setDeviceType(deviceReaVo.getDeviceType());
        deviceListByNosReqVO.setPowerLeve(deviceReaVo.getPowerLeve());
        deviceListByNosReqVO.setOnlineStatus(deviceReaVo.getOnlineStatus());
        deviceListByNosReqVO.setPowerStatus(deviceReaVo.getPowerStatus());
        List<String> deviceNolist = new ArrayList<>();
        List<PullDeviceApiVo> pullList = new ArrayList<>();
        try {
            ResultModel<List<PullDeviceApiVo>> pullDeviceApiVoList = deviceApi.findDeviceList(deviceListByNosReqVO);
            log.info("根据设备号，电量在线状态 列表批量查询设备列表接口返回:{}", JSONObject.toJSONString(pullDeviceApiVoList));
            if (pullDeviceApiVoList.getCode().equals("0")) {
                if (CollectionUtils.isEmpty(pullDeviceApiVoList.getData())) {
                    //没有设备
                    return CommonResult.success(reaVoList);
                } else {
                    pullList = pullDeviceApiVoList.getData();
                    deviceNolist = pullList.stream().map(PullDeviceApiVo::getDeviceNo).collect(Collectors.toList());
                }
            }
        } catch (Exception e) {
            log.info("根据设备号，电量在线状态 列表批量查询设备列表接口返回:{}", e.getStackTrace());
        }

        //查询
        deviceReaVo.setDeviceNos(deviceNolist);
        log.info("查询房间的设备信息参数:{}", deviceReaVo);
        List<DeviceReaVo> list1 = iotDeviceRepository.getDeviceListNoPages(deviceReaVo);
        if (!CollectionUtils.isEmpty(list1)) {
            for (int i = 0; i < list1.size(); i++) {
                DeviceReaVo deviceReaVo1 = new DeviceReaVo();
                deviceReaVo1.setRoomName(list1.get(i).getRoomName());
                deviceReaVo1.setUnitName(list1.get(i).getUnitName());
                deviceReaVo1.setIsWhole(list1.get(i).getIsWhole());
                deviceReaVo1.setSuperId(list1.get(i).getSuperId());
                deviceReaVo1.setIsConcentrated(list1.get(i).getIsConcentrated());
                deviceReaVo1.setDeviceNo(list1.get(i).getDeviceNo());
                deviceReaVo1.setDeviceType(list1.get(i).getDeviceType());
                deviceReaVo1.setDeviceThirdNo(list1.get(i).getDeviceThirdNo());
                for (PullDeviceApiVo apiVo : pullList) {
                    if (apiVo.getDeviceNo().equals(deviceReaVo1.getDeviceNo())) {
                        deviceReaVo1.setBatteryLevel(apiVo.getBatteryLevel());
                        deviceReaVo1.setOnlineStatus(apiVo.getOnlineStatus());
                        deviceReaVo1.setPowerStatus(apiVo.getPowerStatus());
                        deviceReaVo1.setBrandNo(apiVo.getBrandNo());
                        deviceReaVo1.setApiNo(apiVo.getApiNo());
                        deviceReaVo1.setPrice(apiVo.getPrice());
                        deviceReaVo1.setCurrentReading(apiVo.getCurrentReading());
                        deviceReaVo1.setRemainingAmount(apiVo.getRemainingAmount());
                        deviceReaVo1.setUpdateTime(apiVo.getReportTime());
                    }
                }
                reaVoList.add(deviceReaVo1);
            }
        }
        return CommonResult.success(reaVoList);
    }

    @Override
    public List<RoomDeviceStairVo> getBeforeDevice(Long roomHouseId) {
        List<RoomDeviceStairVo> roomDeviceStairVoList = new ArrayList<>();
        //根据房源id获取对应设备编号
        List<DeviceReaVo> deviceId = iotDeviceRepository.getDeviceMapping(roomHouseId);
        if (deviceId.size() > 0) {
            for (DeviceReaVo deviceReaVo : deviceId) {
                //根据设备编号查询阶梯水电
                CommonResult<List<PriceInfo>> result = iotRoomDeviceApi.getDevicePrice(deviceReaVo.getDeviceNo(), deviceReaVo.getDeviceType());
                log.info("阶梯水电result:" + JSONObject.toJSONString(result));
                List<PriceInfo> priceInfos = result.getCheckedData();
                if (priceInfos.size() > 0) {
                    //获取价格
                    ResultModel<DevicePriceVo> resultModel = deviceApi.getCurrentReading(deviceReaVo.getDeviceNo(), deviceReaVo.getDeviceType());
                    DevicePriceVo devicePriceVo = resultModel.getData();
                    log.info("阶梯水电价格resultModel:" + JSONObject.toJSONString(resultModel));
                    if (null != devicePriceVo) {
                        RoomDeviceStairVo stairVo = new RoomDeviceStairVo();
                        stairVo.setPrice(getPrice(BigDecimal.valueOf(devicePriceVo.getReadAccount()), priceInfos).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        stairVo.setAmount(devicePriceVo.getAmount());
                        stairVo.setRead(devicePriceVo.getRead());
                        stairVo.setDasageDate(devicePriceVo.getSageTime());
                        stairVo.setDeviceNo(deviceReaVo.getDeviceNo());
                        stairVo.setDeviceThirdNo(deviceReaVo.getDeviceThirdNo());
                        if (deviceReaVo.getDeviceType().equals("hot_watermeter")) {
                            stairVo.setDeviceType("热水表");
                        } else if (deviceReaVo.getDeviceType().equals("cold_watermeter")) {
                            stairVo.setDeviceType("冷水表");
                        } else if (deviceReaVo.getDeviceType().equals("ammeter")) {
                            stairVo.setDeviceType("电表");
                        }
                        roomDeviceStairVoList.add(stairVo);
                    }
                }
            }
        }
        return roomDeviceStairVoList;
    }

    @Override
    public List<RoomDeviceStairVo> getlaterDevice(Long roomHouseId, List<String> feeType) {
        List<RoomDeviceStairVo> laterDevice = new ArrayList<>();
        List<RoomSdiotReadingOrder> roomSdiotReadingOrders = roomSdiotReadingOrderRecordService.getreadingOrderByRoomId(roomHouseId, feeType);
        if (roomSdiotReadingOrders.size() > 0) {
            for (RoomSdiotReadingOrder readingOrder : roomSdiotReadingOrders) {
                RoomSdiotReadingOrderRecord roomSdiotReadingOrderRecord = roomSdiotReadingOrderRecordService.getRoomSdiotReadingOrderRecord(readingOrder.getId());
                RoomDeviceStairVo roomDeviceStairVo = new RoomDeviceStairVo();
                if (null != roomSdiotReadingOrderRecord) {
                    roomDeviceStairVo.setDasageDate(roomSdiotReadingOrderRecord.getLastTimeReadingTime());
                    roomDeviceStairVo.setAmount(roomSdiotReadingOrderRecord.getFee().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    roomDeviceStairVo.setPrice(roomSdiotReadingOrderRecord.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    roomDeviceStairVo.setRead(roomSdiotReadingOrderRecord.getCurrentReadingCount().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    if (readingOrder.getFeeType().equals("热水费")) {
                        roomDeviceStairVo.setDeviceType("热水表");
                    } else if (readingOrder.getFeeType().equals("冷水费")) {
                        roomDeviceStairVo.setDeviceType("冷水表");
                    } else if (readingOrder.getFeeType().equals("电费")) {
                        roomDeviceStairVo.setDeviceType("电表");
                    }
                    laterDevice.add(roomDeviceStairVo);
                }
            }
        }
        return laterDevice;
    }

    private BigDecimal getPrice(BigDecimal currentTotal, List<PriceInfo> list) {
        if (CollectionUtil.isEmpty(list)) {
            return new BigDecimal(0);
        }
        BigDecimal price = BigDecimal.ZERO;
        for (int i = 0; i < list.size(); i++) {
            PriceInfo s = list.get(i);
            if (currentTotal.compareTo(s.getRead()) > 0) {
                return s.getPrice();
            }
        }
        return price;
    }
}
